<template>
    <div class="container">
        <div class="header">
           <p>新增/修改账户</p>
       </div>
       <div class="main">
           <el-form :model="user" :rules="rules" ref="user" label-width="120px" class="">
             <el-form-item label="用户名" prop="userName">
               <el-input v-model="user.userName" placeholder="请输入用户名"></el-input>
             </el-form-item>
               <!--<el-form-item label="手机号" prop="mobile">-->
                   <!--<el-input v-model="user.mobile" placeholder="请输入手机号"></el-input>-->
               <!--</el-form-item>-->
              <el-form-item label="密码" prop="password">
                  <el-input v-model="user.password" placeholder="请输入密码"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input v-model="user.confirmPassword" placeholder="请确认密码"></el-input>
              </el-form-item>
             <el-form-item label="账号名" prop="loginName">
               <el-input v-model="user.loginName" placeholder="请输入账号名"></el-input>
             </el-form-item>
             <el-form-item label="角色" prop="roleId">
               <el-select v-model='user.roleId' placeholder='-请选择-'>
                 <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value"></el-option>
               </el-select>
             </el-form-item>
              <el-form-item>
                  <el-button type="primary"  @click="handleSave('user')">保存</el-button>
                  <el-button type="info" @click="backList">返回</el-button>
              </el-form-item>
            </el-form>
        </div>


    </div>
</template>

<script>
let CONSTANT = require('../../constant/constant.js');
let common = require("../../common.js");
export default {
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            }
            else if (value !== this.user.password) {
                callback(new Error('两次输入密码不一致!'));
            }
            else {
                callback();
            }
        };
        var validateMobile = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入手机号码'));
            }
            else if (!(/^1[34578]\d{9}$/.test(value))) {
                callback(new Error('手机号码不合法!'));
            }
            else {
                callback();
            }
        };
      var validateEmail= (rule, value, callback) => {
        if (!(/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(value))) {
          callback(new Error('邮箱格式不正确!'));
        } else{
          callback();
        }
      };
        return {
            id:'',
          upLoadUrl:"",
            user: {
              "avatar": "",
              "userName": "",
              "password": "",
              "roleId": null,
              "loginName": "",
            },
          roleList:[],
          pageUrlIndex:null,
            rules: {
              mobile: [
                { required: true, message: '请输入手机号', trigger: 'blur' },
              ],
              userName: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
              password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max:18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
                ],
              confirmPassword: [
                    { required: true, message: '请确认密码', trigger: 'blur' },
                    { validator: validatePass, trigger: 'blur' }
                ],
                loginName: [
                    { required: true, message: '请输入账号名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
//                mobile: [
//                    { required: true, message: '请输入手机号码', trigger: 'blur' },
//                    { validator: validateMobile, trigger: 'blur' }
//                ],
                roleId:[
                    { required: true, message: '请选择角色类型', trigger: 'blur' },
                ],
//              enable:[
//                { required: true, message: '请选择启用状态', trigger: 'blur' },
//              ],
//              email:[
//                { required: true, message: '请输入邮箱', trigger: 'blur' },
//                { validator: validateEmail, trigger: 'blur' }
//              ],
//              avatar:[
//                { required: true, message: '请选择邮箱', trigger: 'blur' },
//              ],
            },
          avatarUrl: ''
        }
    },
    mounted() {
        this.id = this.$router.currentRoute.query.id;
        this.pageUrlIndex = this.$router.currentRoute.query.pageIndex;
        if(this.id){
           this.getUserById();
          this.getRoleList();
        }else  {
          this.getRoleList();
        }
    },
    methods: {
      myUpload() {},
        backList:function(){
            this.$router.push({name:'accountList',params:{'pageIndex':this.pageUrlIndex}});
        },
        getRoleList:function(){
            let url = CONSTANT.URL.roleList1;
            common.post(url, {
              pageIndex:1,
              pageSize: 1000
            },(res)=>{
                let data = res.data.bussData;
                data.map(function(item){
                    item["value"] = item.id;
                    item["label"] = item.roleName;
                })
                this.roleList = data;
            });
        },
        getUserById:function(){
           let url = CONSTANT.URL.accountDetail;
           common.post1(url,{id: this.id},(res)=>{
                if(res.code == 200){
                    let data = res.data.bussData;
                    this.user = data;
                    this.user.password = '';
                    this.avatarUrl = data.avatarUrl
                    this.user.roleId = JSON.parse(data.roleId)
                }
            })
        },
      beforeCoverUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
          return false;
        }
        let url =
          CONSTANT.URL.COMMON.upload + "?suffix="+
          file.name.split(".")[1] +
          "&contentType=" +
          file.type;
        // suffix:file.name.split(".")[1],   // 文件后缀  png
        // contentType:file.type             // 文件类型  image/png
        common.post(url, "", res => {
          let data = res.data.bussData;
          common.uploadFile(data.uploadUrl, file, file.type, res => {
            this.user.avatar = data.fileKey;
            this.avatarUrl = data.downloadUrl;
          });
        });
      },
        getRoleId:function(event){
            this.user.roleId = event;
        },
        handleSave:function(formName){
            this.$refs[formName].validate((valid) => {
                console.log(valid)
                if (valid) {
                    this.user.id = this.id || ''
                  if (!this.user.id) {
                    let url = CONSTANT.URL.accountAdd;
                    common.post(url,this.user,(res)=>{
                      if(res.code == 200) {
                        this.$message({
                          type: 'success',
                          message: '保存账户信息成功！'
                        });
                        if(!!this.pageUrlIndex){
                          this.$router.push({name:'accountList',params:{'pageIndex':this.pageUrlIndex}});
                        }else{
                          this.$router.push("/accountList");
                        }
                      }
                      else{
                        this.$message({
                          type: 'warning',
                          message: res.data.errMsg
                        });
                      }
                    })
                  } else {
                    let url = CONSTANT.URL.accountUpdate;
                    common.post(url,this.user,(res)=>{
                      if(res.code == 200) {
                        this.$message({
                          type: 'success',
                          message: '保存账户信息成功！'
                        });
                        if(!!this.pageUrlIndex){
                          this.$router.push({name:'accountList',params:{'pageIndex':this.pageUrlIndex}});
                        }else{
                          this.$router.push("/accountList");
                        }
                      }
                      else{
                          this.$message({
                              type: 'warning',
                              message: res.data.errMsg
                          });
                      }
                    })
                  }

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        beforeAvatarUpload(index, file) {
          const isLt2M = file.size / 1024 / 1024 < 2;
          if (!isLt2M) {
            this.$message.error("上传头像图片大小不能超过 2MB!");
            return false;
          }
          let url =
            CONSTANT.URL.SYSTEM.ADMINUPLOADFILE +
            file.name.split(".")[1] +
            "?contentType=" +
            file.type;
          common.get(url, "", res => {
            let data = res.data.bussData;
            common.uploadFile(data.uploadUrl, file, file.type, res => {
              this.user.avatar = data.fileKey;
              this.user.avatarUrl = data.downloadUrl;
            });
          });
        },
    },

}
</script>
